//
//  HYPCImportViewController.m
//  XPlayer
//
//  Created by liguoqing on 2023/9/8.
//  PC导入

#import "HYPCImportViewController.h"
#import "HYCSMIPHelper.h"
#import "HYPCImportViewModel.h"
#import <GCDWebServer/GCDWebUploader.h>
#import "HYWifiImportTipView.h"
#import "HYPCImageHeaderView.h"
#import "HYPCImportViewCell.h"
#import "HYWifiImportViewCell.h"
#import "HYSettingHeadView.h"

@interface HYPCImportViewController ()<GCDWebUploaderDelegate,UITableViewDelegate,UITableViewDataSource>
{
    GCDWebUploader * _webServer;
}

@property (nonatomic, strong) HYPCImportViewModel *viewModel;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) HYWifiImportTipView *tipView;

@property (nonatomic, strong) NSString *ipAdress;

@property (nonatomic, assign) BOOL fileImport;

@end

@implementation HYPCImportViewController

- (void)dealloc
{
    CLog(@"dealloc -- %@",[self class]);
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationBarView.titleLabel.text = NSLocalizedString(@"文件导入", nil);
    self.view.backgroundColor = AppBgThemeColor;
    [self configWebSever];
    [self configUI];
    [self addNetStatusChangeObserver];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    dispatch_queue_t referQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0); //降低线程优先级
    dispatch_async(referQueue, ^{
        [self closeWebSever];
    });

    if (self.fileImport) {
        if(self.refreshBlock){
            self.refreshBlock();
        }
    }
}

- (void)configUI
{
    [self.view addSubview:self.tipView];
    [self.tipView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view);
        make.height.mas_equalTo(44+HOME_BAR_HEIGHT);
    }];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.navigationBarView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.tipView.mas_top);
    }];
}

- (void)addNetStatusChangeObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netStatusChangeNotify:) name:kNetStatusHelperChangedNotification object:nil];
}

- (void)netStatusChangeNotify:(NSNotification *)notify
{
    NSDictionary *netInfo = notify.object;
    NetworkStatus status = [netInfo[@"netstatus"] integerValue];
    if(status != ReachableViaWiFi){
        [HYHub showMessage:NSLocalizedString(@"wifi网络已断开", nil)];
    }else{
        [HYHub showMessage:NSLocalizedString(@"wifi网络已连接", nil)];
    }
}

- (void)configWebSever
{
    if([HYNetWorkManager shareManager].currentReachabilityStatus != ReachableViaWiFi){
        [HYHub showMessage:NSLocalizedString(@"请连接wifi网络", nil)];
        return;
    }
    // 创建webServer，设置根目录
    _webServer = [[GCDWebUploader alloc] initWithUploadDirectory:[HYFileManager wifiImportFileDocumentPath]];
    // 设置代理
    _webServer.delegate = self;
    _webServer.allowHiddenItems = YES;
    
    // 限制文件上传类型
    _webServer.allowedFileExtensions = [[HYFileManager shareManager] fetchImportfileTypes];
    // 设置网页标题
    _webServer.title = @"VPlayer";
    // 设置展示在网页上的文字(开场白)
    _webServer.prologue = NSLocalizedString(@"欢迎使用VPlayer的WIFI管理平台", nil);
    // 设置展示在网页上的文字(收场白)
    _webServer.epilogue = NSLocalizedString(@"VPlayer制作", nil);
    
    
    if ([_webServer startWithPort:8080 bonjourName:nil]) {
        self.ipAdress = [NSString stringWithFormat:@"http://%@:%zd/", [HYCSMIPHelper deviceIPAdress], _webServer.port];
    } else {
        self.ipAdress = NSLocalizedString(@"网页服务未运行!", nil);
    }
}

- (void)closeWebSever
{
    [_webServer stop];
    _webServer = nil;
}

#pragma mark GCDWebUploaderDelegate
- (void)webUploader:(GCDWebUploader*)uploader didUploadFileAtPath:(NSString*)path
{
    [HYHub showMessage:NSLocalizedString(@"文件上传成功,请返回上级页面查看！", nil)];
    self.fileImport = YES;
}
#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HYPCImportViewCell *cell;
    if(indexPath.section == 0){
        cell = [tableView dequeueReusableCellWithIdentifier:@"HYPCImportViewCell" forIndexPath:indexPath];
    }else{
        cell = [tableView dequeueReusableCellWithIdentifier:@"HYWifiImportViewCell" forIndexPath:indexPath];
        cell.thirdLabel.text = [NSString stringWithFormat:@"    %@",self.ipAdress];
    }
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    HYSettingHeadView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"HYSettingHeadView"];
    if (section == 0) {
        [headerView setHeadTitle:NSLocalizedString(@"PC导入", nil) withTextAlignment:NSTextAlignmentLeft];
    }else{
        [headerView setHeadTitle:NSLocalizedString(@"WIFI导入", nil) withTextAlignment:NSTextAlignmentLeft];
    }
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}

#pragma mark - loadLazy
- (UITableView *)tableView
{
    if(!_tableView){
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = kClearColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.estimatedRowHeight = 175;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        [_tableView registerClass:[HYPCImportViewCell class] forCellReuseIdentifier:@"HYPCImportViewCell"];
        [_tableView registerClass:[HYWifiImportViewCell class] forCellReuseIdentifier:@"HYWifiImportViewCell"];
        [_tableView registerClass:[HYSettingHeadView class] forHeaderFooterViewReuseIdentifier:@"HYSettingHeadView"];
    }
    return _tableView;
}

#pragma mark - loadlazy
- (HYWifiImportTipView *)tipView
{
    if(!_tipView){
        _tipView = [[HYWifiImportTipView alloc]init];
    }
    return _tipView;
}

- (HYPCImportViewModel *)viewModel
{
    if(!_viewModel){
        _viewModel = [[HYPCImportViewModel alloc]init];
    }
    return _viewModel;
}

@end
